package cn.waka.sys.admin.controller;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.App;
import cn.waka.sys.admin.object.AppVersion;
import cn.waka.sys.admin.object.Page;
import cn.waka.sys.admin.object.Result;
import cn.waka.sys.admin.service.AppService;
import cn.waka.sys.admin.service.RedisService;
import cn.waka.sys.admin.utils.Validator;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("/app")
@SessionAttributes
public class AppController extends BaseController{

	
	@Autowired
	private AppService appService;
	@Autowired
	private RedisService redisService;
	
	@GetMapping(path = "/index",name="应用分页")
	public ModelAndView pageList(HttpServletRequest req, HttpServletResponse res){
		String pStr=req.getParameter("page");
		Page p=new Page();
		if(pStr!=null&&Validator.isNum(pStr)){
			p.setPage(Integer.parseInt(pStr));
		}
		String sizeStr=req.getParameter("size");
		if(sizeStr!=null&&Validator.isNum(sizeStr)){
			p.setSize(Integer.parseInt(sizeStr));
		}
		
	
		ModelAndView mv=new ModelAndView();
		
		
		appService.findPage(p,null);
		
		mv.addObject("page", p);
		mv.addObject("search_param", "");
		return mv;
		
	}
	
	@GetMapping(path = "/version/index",name="版本分页")
	public ModelAndView pageVersionList(HttpServletRequest req, HttpServletResponse res){
		String pStr=req.getParameter("page");
		Page p=new Page();
		if(pStr!=null&&Validator.isNum(pStr)){
			p.setPage(Integer.parseInt(pStr));
		}
		String sizeStr=req.getParameter("size");
		if(sizeStr!=null&&Validator.isNum(sizeStr)){
			p.setSize(Integer.parseInt(sizeStr));
		}
		
		String appIdStr=req.getParameter("app_id");
		if(appIdStr==null||!Validator.isNum(appIdStr)){
			appIdStr="0";
		}
		int appId=Integer.parseInt(appIdStr);
		
		ModelAndView mv=new ModelAndView();
		
		appService.findVersionPage(p,appId);
		p.addParam("app_id", appIdStr);
		mv.addObject("page", p);
		mv.addObject("app_id", appIdStr);
		mv.addObject("search_param", "");
		return mv;
		
	}
	
	@GetMapping(path = "/log/index", name="日志分页")
	public ModelAndView pageLogList(HttpServletRequest req, HttpServletResponse res){
		String pStr=req.getParameter("page");
		Page p=new Page();
		if(pStr!=null&&Validator.isNum(pStr)){
			p.setPage(Integer.parseInt(pStr));
		}
		String sizeStr=req.getParameter("size");
		if(sizeStr!=null&&Validator.isNum(sizeStr)){
			p.setSize(Integer.parseInt(sizeStr));
		}
		
		String appIdStr=req.getParameter("app_id");
		if(appIdStr==null||!Validator.isNum(appIdStr)){
			appIdStr="0";
		}
		int appId=Integer.parseInt(appIdStr);
		
		ModelAndView mv=new ModelAndView();
		
		appService.findLogPage(p,appId);
		p.addParam("app_id", appIdStr);
		mv.addObject("page", p);
		mv.addObject("app_id", appIdStr);
		mv.addObject("search_param", "");
		return mv;
		
	}
	@GetMapping(path = "/add", name="添加应用")
	public ModelAndView add(HttpServletRequest req, HttpServletResponse res){
		
		App obj=new App();
		ModelAndView mv=new ModelAndView("/app/edit");
		mv.addObject("obj", obj);
		return mv;
	}
	@GetMapping(path = "/edit", name="修改日志")
	public ModelAndView edit(HttpServletRequest req, HttpServletResponse res){
		String idStr=req.getParameter("id");
		
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		App obj=null;
		if(id==0){
			obj=new App();
		}else{
			obj=appService.findById(id);
			if(obj==null){
				obj=new App();
			}
		}
		
		ModelAndView mv=new ModelAndView();
		mv.addObject("obj", obj);
		return mv;
	}
	@GetMapping(path = "/forbid",name="下线应用")
	public  @ResponseBody Result forbid(HttpServletRequest req, HttpServletResponse res, @SessionAttribute("uid") int uid){
		String idStr=req.getParameter("id");
		if(idStr==null){
			return error(0,"ID为空");
		}
		if(!Validator.isNum(idStr)){
			return error(0,"ID不是数字");
		}
		
		int id=Integer.parseInt(idStr);
		boolean rs=appService.updateStatus(id, 0,uid);
		
		if(rs){
			return error(1,"操作成功！");
		}
		return error(0,"操作失败！");
	}
	
	@GetMapping(path = "/resume",name="上线应用")
	public @ResponseBody Result resume(HttpServletRequest req, HttpServletResponse res, @SessionAttribute("uid") int uid){
		String idStr=req.getParameter("id");
		if(idStr==null){
			return error(0,"ID为空");
		}
		if(!Validator.isNum(idStr)){
			return error(0,"ID不是数字");
		}
		
		int id=Integer.parseInt(idStr);
		boolean rs=appService.updateStatus(id, 1,uid);
		
		if(rs){
			return error(1,"操作成功！");
		}
		return error(0,"操作失败！");
	}

	

	
	@RequestMapping(path = "/save", name="保存应用")
	public @ResponseBody Result save(HttpServletRequest req, HttpServletResponse res, HttpSession sess){
		String idStr=req.getParameter("id");
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		String name=req.getParameter("name");
		if(name==null){
			return error(0,"名称不能为空！");
		}
		
		String typeStr=req.getParameter("type");
		
		if(typeStr==null||!Validator.isNum(typeStr)){
			return error(0,"类型错误！");
		}
		
		String expiredTime=req.getParameter("expiredTime");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			sdf.parse(expiredTime);
		} catch (ParseException e) {
			
			e.printStackTrace();
			return error(0,"时间格式不正确！");
		}
		int userId=(int)sess.getAttribute("uid");
		
		App app=new App();
		app.setId(id);
		app.setName(name);
		
		
		app.setExpiredTime(java.sql.Timestamp.valueOf(expiredTime));
		app.setCreateUserId(userId);
		int rs = appService.save(app);
		
		if(rs>0){
			return error(1,"保存成功！");
		}else{
			return error(0,"保存失败！");
		}
	}
	
	
	@RequestMapping(path = "/version/add", name="添加版本")
	public ModelAndView versionAdd(@RequestParam(name="app_id",required=false,defaultValue="0")int appId,HttpServletRequest req, HttpServletResponse res){
		AppVersion obj=new AppVersion();
		obj.setAppId(appId);
		ModelAndView mv=new ModelAndView("/app/version/info");
		
		
		String url = "http://"+req.getServerName();
    	if(appId==1){
    		url += "/client/android.apk";
    	}else if(appId==2){
    		url += "/box/box.apk";
    	}
    	obj.setUrl(url);
    	mv.addObject("vo", obj);
		return mv;
	}
	@RequestMapping(path = "/version/edit", name="修改版本")
	public ModelAndView versionEdit(@RequestParam(name="id",required=false) String idStr,HttpServletRequest req, HttpServletResponse res){
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		AppVersion obj=null;
		if(id==0){
			obj=new AppVersion();
		}else{
			obj=appService.findVersionById(id);
			if(obj==null){
				obj=new AppVersion();
			}
		}
		
		ModelAndView mv=new ModelAndView("/app/version/info");
		mv.addObject("vo", obj);
		return mv;
	}
	
	@RequestMapping(path = "/version/del", name="删除版本")
	public @ResponseBody Result versionDel(HttpServletRequest req, HttpServletResponse res){
		String idStr=req.getParameter("id");
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
		if(id==0){
			return error(0,"ID不存在！");
		}
		AppVersion obj=appService.findVersionById(id);
		int appId = obj.getAppId();
		
		int rs=appService.delVersionById(id);
		if(rs==0){
			return error(0,"删除失败！");
		}
		
		//更新最高版本信息到redis
		Map<String,String> maxVersoin = appService.getMaxVersion(appId);
		Map<String,Object> value = new HashMap<String,Object>();
		value.put("version", maxVersoin.get("version"));
		value.put("type", maxVersoin.get("type"));
		value.put("url", maxVersoin.get("url"));
		value.put("mark", maxVersoin.get("mark"));
		JSONObject jsonObject = JSONObject.fromObject(value);
		redisService.set(maxVersoin.get("app_key")+"_version", jsonObject.toString());
				
		return error(1,"删除成功！");
	}
	
	@PostMapping(path = "/version/save", name="保存版本")
	public  @ResponseBody Result versionSave(@RequestParam(name="app_id",required=false)int appId,@RequestParam(name="id",required=false)String idStr,@RequestParam(name="version",required=false)String version,@RequestParam(name="type",required=false)String typeStr,@RequestParam(name="mark",required=false)String mark,@RequestParam(name="url",required=false)String url,@SessionAttribute("uid") int userId){
		
		if(typeStr==null||!Validator.isNum(typeStr)){
			return error(0,"类型不正确！");
		}
		int id=0;
		if(idStr!=null&&Validator.isNum(idStr)){
			id=Integer.parseInt(idStr);
		}
	
		if(url==null){
			return error(0,"请输入下载地址!");
		}
		if(!Validator.isVersion(version)){
			return error(0,"请输入正确的版本号!");
		}
		if(!Validator.isUrl(url)){
			return error(0,"请输入正确的下载地址!");
		}
		
		
		
		AppVersion v=new AppVersion();
		v.setId(id);
		v.setCreateTime(new Timestamp(System.currentTimeMillis()));
		v.setMark(mark);
		v.setUrl(url);
		v.setUserId(userId);
		v.setAppId(appId);
		v.setVersion(version);
		v.setType(Integer.parseInt(typeStr));
		
		int rs=appService.saveVersion(v);
		
		if(rs==0){
			return error(0,"保存失败！");
		}else if(rs==-1){
			return error(0,"版本号已存在！");
		}
		
		//更新最高版本信息到redis
		Map<String,String> maxVersoin = appService.getMaxVersion(appId);
		Map<String,Object> value = new HashMap<String,Object>();
		value.put("version", maxVersoin.get("version"));
		value.put("type", maxVersoin.get("type"));
		value.put("url", maxVersoin.get("url"));
		value.put("mark", maxVersoin.get("mark"));
		JSONObject jsonObject = JSONObject.fromObject(value);
		redisService.set(maxVersoin.get("app_key")+"_version", jsonObject.toString());
		
		return error(1,"保存成功！");
	}
}
